package cn.acyou.leo.product.web.aop;

import cn.acyou.leo.framework.context.AppContext;
import cn.acyou.leo.framework.util.IPUtil;
import cn.acyou.leo.framework.util.SourceUtil;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author youfang
 * @version [1.0.0, 2020/7/28]
 **/
@Slf4j
public class SpringMvcInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws Exception {
        String remoteIp = IPUtil.getClientIp(request);
        String localIp = IPUtil.getLocalIP();
        log.info("SpringMvcInterceptor ——>  remoteIP:{}, localIP: {}, 访问路径:{}", remoteIp, localIp, request.getRequestURI());
        AppContext.setIp(remoteIp);
        AppContext.setRequestTimeStamp(System.currentTimeMillis());
        AppContext.setActionUrl(request.getRequestURI());
        AppContext.setClientType(SourceUtil.getClientTypeByUserAgent(request));
        String methodInfo = "";
        String apiRemark = "";
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = ((HandlerMethod) handler);
            methodInfo = handlerMethod.toString();
            Method method = handlerMethod.getMethod();
            ApiOperation annotation = method.getAnnotation(ApiOperation.class);
            if (annotation != null) {
                apiRemark = annotation.value();
            }
        }
        AppContext.setActionApiOperation(methodInfo, apiRemark);
        return true;
    }


    @Override
    public void afterCompletion(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler, Exception ex) throws Exception {
        log.info("SpringMvcInterceptor ——>  访问结束。");
        AppContext.clearThreadLocal();
        PageHelper.clearPage();
    }


}
